﻿/// <reference path="../../knockout-2.1.0.js" />
/// <reference path="../../knockout.mapping-latest.js" />
/// <reference path="../shared/utils.js" />
/// <reference path="../../jquery-1.7.2-vsdoc.js" />
/// <reference path="../../knockout.wrap.js" />
/// <reference path="../../thrid-party/knockout.validation.v0.9.js" />
var ignoredMapping = { ignore: ["Medicos"] };

function EditorViewModel(data, medicos) {
    var self = this;
    self.Id = ko.observable().extend({ numeric: true });
    self.Examenes = ko.observableArray(["GENERAL", "VISION", "AUDICION", "PSICOSENSOMETRICO"]);
    self.UserInfo = ko.observable();
    self.Mensaje = ko.observable();
    self.HaveErrors = ko.observable(false);

    self.FindUser = function () {
        if ($.trim(self.Id()) != "") {
            ajaxGet('/citas/BuscarIndividuo', { id: self.Id() }, function (response) {
                if (!(response.data.length === 0)) {
                    var userinfo = ko.mapping.fromJS(response.data[0]);
                    self.UserInfo(userinfo);
                } else { self.UserInfo(null); }
            });
        };
    };

    self.Save = function () {
        if (self.UserInfo() != null) {
            self.IndividuoId = self.UserInfo().IndividuoId();
            ajax('citas/SaveCita', ko.mapping.toJSON(self, ignoredMapping), function (result) {
                if (result.isValid) {
                    self.Mensaje("La cita para el usuario <b>" + self.UserInfo().Nombres() + " " + self.UserInfo().PrimerApellido() + "</b> fue programada para <b>" + result.fecha + "</b>");
                    $('#modalsaved').modal();
                    dispose();
                } else {
                    self.HaveErrors(true);
                    self.Mensaje(result.message);
                }
            });
        }
    };

    self.Load = function (info) {
        ko.mapping.fromJS(info, {}, this);
        ko.mapping.fromJS(medicos, {}, this);
    };

    if (data)
        self.Load(data);

    function dispose() {
        self.Id(null);
        self.UserInfo(null);
        self.HaveErrors(false);
    }
}

function BuscarUsuarioViewModel(data, queryParametersObservable) {
    var self = this;
    self.Results = ko.observableArray([]);
    self.UserId = ko.observable('');
    self.NoIdentificacionSearch = ko.observable('');
    self.Apellido = ko.observable('');

    /*Paging*/
    self.PageSize = ko.observable(25);
    self.PageIndex = ko.observable(0);
    self.PreviousPage = function () { self.PageIndex(self.PageIndex() - 1); };
    self.NextPage = function () { self.PageIndex(self.PageIndex() + 1); };
    self.MaxPageIndex = ko.computed(function () {
        return Math.ceil(self.Results().length / self.PageSize()) - 1;
    });
    self.PagedResults = ko.computed(function () {
        var size = self.PageSize();
        var start = self.PageIndex() * size;
        return self.Results.slice(start, size + start);
    });
    /*end Paging*/

    self.Mostar = function (selected) {
        location.hash = '/ShowCitas?idIndividuo=' + selected.IndividuoId();
    };

    self.Buscar = function () {
        queryParametersObservable({ id: self.NoIdentificacionSearch(), apellido: self.Apellido() });
        var ss = $.param({ id: self.NoIdentificacionSearch(), apellido: self.Apellido() });
        location.hash = "/Buscar?" + ss;
    };

    self.Load = function () {
        self.Results(ko.mapping.fromJS(data)());
    };

    if (data)
        self.Load(data);
}

function CitasDetailViewModel(data) {
    var self = this;
    self.Results = ko.observable();
    self.UserInfo = ko.observable();

    self.Load = function (info) {
        self.Results(ko.mapping.fromJS(info.data));
        self.UserInfo(ko.mapping.fromJS(info.userInfo));
    };

    if (data)
        self.Load(data);
}

function CitasVM() {
    var self = this;
    self.Pages = ['Buscar', 'Crear'];
    self.CurrentPage = ko.observable();
    self.BuscarUsuario = ko.observable();
    self.CitaEditor = ko.observable();
    self.ShowCitas = ko.observable();
    self.Time = ko.observable();

    self.Load = function (data, page) {
        self.RefreshPages();
        var start = new Date().getTime();
        self.CurrentPage(page);
        if (self.CurrentPage() == 'Crear')
            self.CitaEditor(new EditorViewModel(data.data, data.values));
        if (self.CurrentPage() == 'Buscar')
            self.BuscarUsuario(new BuscarUsuarioViewModel(data.data, self.QueryParameters));
        if (self.CurrentPage() == 'detail')
            self.ShowCitas(new CitasDetailViewModel(data));
        self.Time((new Date().getTime() - start) / 1000 + 'ms');
    };

    self.QueryParameters = ko.observable();

    self.RefreshPages = function () {
        self.BuscarUsuario(null);
        self.CitaEditor(null);
        self.ShowCitas(null);
        self.QueryParameters(null);
    };

    var crear = {
        path: 'Crear',
        server: '/citas/FormJs',
        data: ko.observable({ page: "Crear" }),
        call: function (data) { self.Load(data, 'Crear'); }
    };
    var buscar = {
        path: 'Buscar',
        server: '/citas/BuscarIndividuo',
        data: self.QueryParameters,
        call: function (data) { self.Load(data, 'Buscar'); }
    };
    var detail = {
        path: 'ShowCitas',
        server: '/citas/ShowCitas',
        call: function (data) { self.Load(data, 'detail'); }
    };

    Routes([crear, buscar, detail]).run('/Citas#/Crear');
}

function startApp() {
    ko.applyBindings(new CitasVM(), document.getElementById("CitasBox_binding"));
}

$(function () {
    startApp();
});